import uvicorn, argparse
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from common.logger import logger, setup_logging
from common.middleware import log_middleware
from routers import testRouter
from models.TestModels import TestModel


app = FastAPI(
    title="FastAPI Demo Server",
    version="0.0.1"
)

# 添加中间件
app.middleware("http")(log_middleware)

# 跨域设置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 引入routers
app.include_router(testRouter.router)


# GET请求
@app.get("/test_get")
async def test_get():
    return "这是一个GET请求的响应"


# POST请求
@app.post("/test_post")
async def test_post(model:TestModel):
    return {
        "msg": "这是一个POST请求的响应",
        "model": model
    }


# 服务启动时回调函数
@app.on_event("startup")
def startup_event():
    logger.success("应用程序已启动")
    logger.success(f"访问地址：http://{host}:{port}")


# 服务关闭时回调函数
@app.on_event("shutdown")
def shutdown_event():
    logger.warning("应用程序已关闭")


# 启动api的方法
def run_api(host, port, ssl_keyfile, ssl_certfile):
    setup_logging()
    if ssl_keyfile and ssl_certfile:
        uvicorn.run(app, host, port, ssl_keyfile, ssl_certfile, log_config=None)
    else:
        uvicorn.run(app, host=host, port=port, log_config=None)


# main方法
if __name__ == "__main__":
    # parser用于解析启动命令中的参数，如：python main.py --host localhost --prot 8090
    # 没有接收到对应参数时使用default的值，如没有default则为None
    parser = argparse.ArgumentParser(prog='FastAPI Demo', description='FastAPI Demo Server')
    parser.add_argument("--host", type=str, default="localhost")
    parser.add_argument("--port", type=int, default=8080)
    parser.add_argument("--ssl_keyfile", type=str)
    parser.add_argument("--ssl_certfile", type=str)
    # 初始化消息
    args = parser.parse_args()
    global host, port
    host = args.host
    port = args.port
    run_api(host, port, args.ssl_keyfile, args.ssl_certfile)
